<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="queryForm" :inline="true" :model="queryParams" size="small">
        <el-form-item prop="params.name">
          <el-input
            v-model="queryParams.params.name"
            class="filter-item"
            clearable
            placeholder="教师姓名"
          />
        </el-form-item>
        <el-form-item prop="params.phone">
          <el-input
            v-model="queryParams.params.phone"
            class="filter-item"
            clearable
            placeholder="电话号码"
          />
        </el-form-item>
        <el-form-item prop="params.sex">
          <el-select v-model="queryParams.params.sex" clearable placeholder="性别">
            <el-option v-for="item in sexList" :key="item.id" :label="item.value" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item prop="params.position">
          <el-select v-model="queryParams.params.position" clearable placeholder="职位">
            <el-option v-for="item in positionList" :key="item.id" :label="item.value" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item prop="params.positionRank">
          <el-select v-model="queryParams.params.positionRank" clearable placeholder="职位级别">
            <el-option v-for="item in positionRankList" :key="item.id" :label="item.value" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item prop="params.nation">
          <el-select v-model="queryParams.params.nation" placeholder="民族">
            <el-option v-for="item in nationList" :key="item.id" :label="item.value" :value="parseInt(item.code)" />
          </el-select>
        </el-form-item>
        <el-form-item prop="params.socialPresence">
          <el-select v-model="queryParams.params.socialPresence" clearable placeholder="社会面貌">
            <el-option v-for="item in socialPresenceList" :key="item.id" :label="item.value" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item prop="params.documentType">
          <el-select v-model="queryParams.params.documentType" clearable placeholder="证件类型">
            <el-option v-for="item in documentTypeList" :key="item.id" :label="item.value" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item prop="params.documentNumber">
          <el-input v-model="queryParams.params.documentNumber" clearable placeholder="证件号码" />
        </el-form-item>
        <!-- 按钮 -->
        <el-button
          v-permission="['/information/teacher/search']"
          v-waves
          class="filter-item"
          icon="el-icon-search"
          size="small"
          style="margin-left: 10px;"
          type="primary"
          @click="getDataList"
        >查询
        </el-button>
        <el-button
          v-permission="['/information/teacher/add']"
          v-waves
          class="filter-item"
          icon="el-icon-plus"
          size="small"
          type="primary"
          @click="handleOpenDialog('add')"
        >新增
        </el-button>
        <el-button
          v-permission="['/information/teacher/search']"
          v-waves
          class="filter-item"
          icon="el-icon-refresh"
          size="small"
          type="primary"
          @click="resetQueryForm"
        >重置
        </el-button>
        <el-button
          v-permission="['/information/student/export']"
          v-waves
          class="filter-item"
          icon="el-icon-download"
          size="small"
          type="warning"
          @click="handleExport"
        >导出
        </el-button>
        <el-form-item style="position: absolute; right: 2%">
          <el-tooltip class="item" content="自定义字段" effect="dark" placement="top-start">
            <el-popover
              placement="bottom"
              title="自定义字段"
              trigger="click"
              width="500"
            >
              <el-collapse v-model="activeNames">
                <el-collapse-item name="1" title="基本属性">
                  <div
                    v-for="item in defaultColumns.slice(0, 10)"
                    :key="item.prop"
                    :label="item"
                    style="display: inline-block;padding-left: 20px;padding-top: 10px"
                  >
                    <el-checkbox v-model="item.isShow" @change="changeColumns(item)">
                      {{ item.label }}
                    </el-checkbox>
                  </div>
                </el-collapse-item>
                <el-collapse-item name="2" title="社会属性">
                  <div
                    v-for="item in defaultColumns.slice(10)"
                    :key="item.prop"
                    :label="item"
                    style="display: inline-block;padding-left: 20px;padding-top: 10px"
                  >
                    <el-checkbox v-model="item.isShow" @change="changeColumns(item)">
                      {{ item.label }}
                    </el-checkbox>
                  </div>
                </el-collapse-item>
              </el-collapse>
              <el-button
                slot="reference"
                style="position: absolute; right: 2%"
                type="success"
              >
                自定义字段
              </el-button>
            </el-popover>
          </el-tooltip>
        </el-form-item>
      </el-form>
    </div>
    <!-- 数据表格 -->
    <el-table
      v-loading="dataListLoading"
      :data="dataList"
      border
      data-list
      fit
      highlight-current-row
      size="small"
      style="width: 100%;"
      @sort-change="handleSortChange"
    >
      <el-table-column :index="shownIndex" align="center" fixed label="序号" type="index" />
      <el-table-column
        v-for="(item,index) in defaultColumns"
        v-if="item.isShow===true"
        :key="index"
        :label="item.label"
        :prop="item.prop"
        :sortable="item.custom"
        show-overflow-tooltip
      />
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="250">
        <template slot-scope="scope">
          <el-button
            v-permission="['/information/teacher/update']"
            v-waves
            size="mini"
            type="primary"
            @click="handleOpenDialog('update', scope.row)"
          >编辑
          </el-button>
          <el-button
            v-permission="['/information/teacher/delete']"
            v-waves
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="queryParams.page"
        :page-size="queryParams.size"
        :page-sizes="[10,20,30, 50]"
        :total="total"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!--新增/编辑对话框    -->
    <el-dialog
      v-loading="dialogLoading"
      :close-on-click-modal="false"
      :title="dialogTitleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      element-loading-text="保存中"
    >
      <el-form
        id="dataForm"
        ref="dataForm"
        :model="dataForm"
        :rules="rules"
        size="small"
      >
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="教师姓名" prop="name">
              <el-input v-model="dataForm.name" placeholder="教师姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="dataForm.phone" placeholder="电话" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="dataForm.email" placeholder="邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="dataForm.sex" clearable placeholder="请选择">
                <el-option v-for="item in sexList" :key="item.id" :label="item.value" :value="parseInt(item.code)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="身高" prop="stature">
              <el-input v-model="dataForm.stature" placeholder="身高" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="体重" prop="weight">
              <el-input v-model="dataForm.weight" placeholder="体重" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="出生日期" prop="birthday">
              <el-date-picker
                v-model="dataForm.birthday"
                placeholder="选择日期"
                style="width: 100%"
                type="datetime"
                @change="changeAge"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="年龄" prop="age">
              <el-input v-model="dataForm.age" placeholder="年龄" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="职位" prop="sex">
              <el-select v-model="dataForm.position" placeholder="请选择">
                <el-option
                  v-for="item in positionList"
                  :key="item.id"
                  :label="item.value"
                  :value="parseInt(item.code)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="职位级别" prop="sex">
              <el-select v-model="dataForm.positionRank" placeholder="请选择">
                <el-option
                  v-for="item in positionRankList"
                  :key="item.id"
                  :label="item.value"
                  :value="parseInt(item.code)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入职日期" prop="entryDate">
              <el-date-picker
                v-model="dataForm.entryDate"
                placeholder="选择日期"
                style="width: 100%"
                type="datetime"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="毕业学校" prop="graduationSchool">
              <el-input v-model="dataForm.graduationSchool" placeholder="毕业学校" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="民族" prop="sex">
              <el-select v-model="dataForm.nation" placeholder="请选择">
                <el-option
                  v-for="item in nationList"
                  :key="item.id"
                  :label="item.value"
                  :value="parseInt(item.code)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="社会面貌" prop="sex">
              <el-select v-model="dataForm.socialPresence" placeholder="请选择">
                <el-option
                  v-for="item in socialPresenceList"
                  :key="item.id"
                  :label="item.value"
                  :value="parseInt(item.code)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="证件类型" prop="sex">
              <el-select v-model="dataForm.documentType" placeholder="请选择">
                <el-option
                  v-for="item in documentTypeList"
                  :key="item.id"
                  :label="item.value"
                  :value="parseInt(item.code)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="证件号码" prop="documentNumber">
              <el-input v-model="dataForm.documentNumber" placeholder="证件号码" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="家庭住址" prop="address">
              <el-input v-model="dataForm.address" autosize placeholder="家庭住址" type="textarea" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="dataForm.remark" autosize placeholder="备注" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus==='add'" size="small" type="primary" @click="handleAdd">确定</el-button>
        <el-button v-if="dialogStatus==='update'" size="small" type="primary" @click="handleUpdate">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>

import { add, del, exportExcel, fetchList, update } from '@/api/information/teacher'
import { typeList } from '@/api/system/dict'
import moment from 'moment'

export default {
  name: 'Teacher',
  data() {
    return {
      total: 0,
      dataList: [],
      directorList: [],
      sexList: [],
      nationList: [],
      positionList: [],
      positionRankList: [],
      socialPresenceList: [],
      documentTypeList: [],
      activeNames: ['1'],
      dataListLoading: false,
      dialogFormVisible: false,
      dialogLoading: false,
      dialogStatus: '',
      dialogTitleMap: {
        add: '新增',
        update: '编辑'
      },
      queryParams: {
        page: 1,
        size: 10,
        params: {
          name: '',
          phone: '',
          sex: '',
          position: '',
          positionRank: '',
          socialPresence: '',
          documentType: '',
          documentNumber: '',
          nation: ''
        }
      },
      dataForm: {
        name: '',
        phone: '',
        email: '',
        sex: '',
        stature: '',
        weight: '',
        birthday: '',
        age: '',
        address: '',
        position: '',
        positionRank: '',
        entryDate: '',
        graduationSchool: '',
        socialPresence: '',
        documentType: '',
        documentNumber: '',
        remark: '',
        nation: ''
      },
      rules: {
        name: [{ required: true, message: '教师名称不能为空', trigger: 'change' }]
      },
      defaultColumns: [
        { prop: 'id', label: 'ID', isShow: true, custom: true },
        { prop: 'name', label: '姓名', isShow: true, custom: false },
        { prop: 'sexName', label: '性别', isShow: true, custom: false },
        { prop: 'age', label: '年龄', isShow: true, custom: true },
        { prop: 'birthday', label: '出生日期', isShow: false, custom: true, width: 120 },
        { prop: 'stature', label: '身高', isShow: false, custom: true },
        { prop: 'weight', label: '体重', isShow: false, custom: true },
        { prop: 'phone', label: '电话', isShow: false, custom: false, width: 120 },
        { prop: 'email', label: '邮箱', isShow: false, custom: false, width: 120 },
        { prop: 'address', label: '家庭住址', isShow: false, custom: false, width: 120 },
        { prop: 'positionName', label: '职位', isShow: true, custom: false },
        { prop: 'positionRankName', label: '职位级别', isShow: true, custom: false },
        { prop: 'entryDate', label: '入职日期', isShow: false, custom: false, width: 120 },
        { prop: 'graduationSchool', label: '毕业学校', isShow: false, custom: false, width: 120 },
        { prop: 'nationName', label: '民族', isShow: false, custom: false },
        { prop: 'socialPresenceName', label: '社会面貌', isShow: false, custom: false },
        { prop: 'documentTypeName', label: '证件类型', isShow: false, custom: false },
        { prop: 'documentNumber', label: '证件号码', isShow: false, custom: false, width: 120 },
        { prop: 'creatorName', label: '创建人', isShow: false, custom: false },
        { prop: 'createdDate', label: '创建时间', isShow: true, custom: true, width: 120 },
        { prop: 'modifierName', label: '编辑人', isShow: false, custom: false },
        { prop: 'modifiedDate', label: '修改时间', isShow: false, custom: false, width: 120 },
        { prop: 'remark', label: '备注', isShow: true, custom: false, width: 120 }
      ]
    }
  },
  computed: {},
  mounted() {
    this.getDataList()
    // 首次进入页面时查找local中是否有存储的显示列
    const str = localStorage.getItem('teacherColumns')
    if (str !== null) {
      this.defaultColumns = JSON.parse(str)
    }
    // 获取性别
    typeList({ type: 'sex' }).then(res => {
      this.sexList = res.data
    })
    // 获取职位
    typeList({ type: 'position' }).then(res => {
      this.positionList = res.data
    })
    // 获取职位级别
    typeList({ type: 'positionRank' }).then(res => {
      this.positionRankList = res.data
    })
    // 获取社会面貌
    typeList({ type: 'socialPresence' }).then(res => {
      this.socialPresenceList = res.data
    })
    // 证件类型
    typeList({ type: 'documentType' }).then(res => {
      this.documentTypeList = res.data
    })
    // 民族
    typeList({ type: 'nation' }).then(res => {
      this.nationList = res.data
    })
  },
  methods: {
    shownIndex(index) {
      return (this.queryParams.page - 1) * this.queryParams.size + index + 1
    },
    handleSortChange(data) {
      console.log('handleSortChange')
      console.log(data)
      if (data.order) {
        if (data.order.indexOf('asc') > -1) {
          this.queryParams.sortOrder = 'asc'
        } else {
          this.queryParams.sortOrder = 'desc'
        }
        this.queryParams.sortName = data.prop
      }
      console.log(this.queryParams)
      this.getDataList()
    },
    // 更改表格的显示列时存储到location中
    changeColumns(val) {
      const num = this.defaultColumns.filter(p => {
        return p.isShow
      })
      if (num.length > 10) {
        this.$message.error('最多选中10个字段')
        // eslint-disable-next-line no-return-assign
        return val.isShow = false
      }
      localStorage.setItem('teacherColumns', JSON.stringify(this.defaultColumns))
    },
    getDataList() {
      this.dataListLoading = false
      fetchList(this.queryParams)
        .then(res => {
          console.log(res)
          this.dataList = res.data.records
          this.total = res.data.total
          this.dataListLoading = false
        })
        .catch(err => {
          console.log(err)
          this.dataLoading = false
        })
    },
    handleOpenDialog(type, rowData) {
      this.resetDataForm()
      this.dialogStatus = type
      this.dialogFormVisible = true
      if (type === 'update') {
        this.dataForm = JSON.parse(JSON.stringify(rowData))
      }
    },
    resetQueryForm() {
      this.$refs['queryForm'].resetFields()
      this.queryParams.page = 1
      this.getDataList()
    },
    resetDataForm() {
      if (this.$refs['dataForm']) {
        // 由于编辑数据的时候会导致表单对象的初始化值发生变更，所以在重置表单前先手动重置表单对象的值
        this.dataForm = {
          name: '',
          phone: '',
          email: '',
          sex: '',
          stature: '',
          weight: '',
          birthday: '',
          age: '',
          address: '',
          position: '',
          positionRank: '',
          entryDate: '',
          graduationSchool: '',
          socialPresence: '',
          documentType: '',
          documentNumber: '',
          remark: '',
          nation: ''
        }
        this.$refs['dataForm'].resetFields()
      }
    },
    handleSizeChange(size) {
      this.queryParams.size = size
      this.getDataList()
    },
    handleCurrentChange(page) {
      this.queryParams.page = page
      this.getDataList()
    },
    handleAdd() {
      // 先进行表单校验
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.dialogLoading = true
          add(this.dataForm)
            .then(res => {
              console.log(res)
              this.$message.success(res.msg || '新增成功')
              this.dialogLoading = false
              this.dialogFormVisible = false
              this.resetDataForm()
              this.getDataList()
            })
            .catch(err => {
              console.log(err)
              this.dialogLoading = false
            })
        }
      })
    },
    handleUpdate() {
      // 先进行表单校验
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.dialogLoading = true
          update(this.dataForm)
            .then(res => {
              console.log(res)
              this.$message.success(res.msg || '修改成功')
              this.dialogLoading = false
              this.dialogFormVisible = false
              this.resetDataForm()
              this.getDataList()
            })
            .catch(err => {
              console.log(err)
              this.dialogLoading = false
            })
        }
      })
    },
    handleDelete(rowData) {
      this.$confirm('是否删除该用户？', '删除提示', { type: 'warning' })
        .then(() => {
          del(rowData)
            .then(res => {
              console.log(res)
              this.$message.success(res.msg || '删除成功')
              this.getDataList()
            })
            .catch(err => {
              this.$message.error(err.msg || '删除失败')
              console.log(err)
            })
        })
        .catch(cancel => {
          console.log(cancel)
        })
    },
    changeAge() {
      this.dataForm.age = moment(new Date()).diff(this.dataForm.birthday, 'years')
    },
    handleExport() {
      console.log('handleExport')
      exportExcel(this.queryParams)
    }
  }
}
</script>
<style scoped>
.el-form .el-select {
  width: 100%;
}

#dataForm .el-form-item {
  margin-top: 14px;
}

.el-row {
  margin-bottom: 20px;
}

:last-child {
  margin-bottom: 0;
}

.el-col {
  border-radius: 4px;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>
